package com.lagou.boot;

import com.lagou.service.UserServiceImpl;
import com.lagou.zookeeper.CreateNode;
import com.lagou.zookeeper.ZkConstant;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerBoot {


    public static void main(String[] args) throws InterruptedException, IOException {
        String hostAddress = InetAddress.getLocalHost()
                                        .getHostAddress();
        int port = (int) (Math.random() * 10000 + 1);
        CreateNode createNode = new CreateNode(hostAddress, port);
        CreateNode.init(createNode);
        //启动服务器
        UserServiceImpl.startServer(hostAddress, port);
        ZooKeeper zooKeeper = CreateNode.zooKeeper;
        Map<String, Long> addressMap = new HashMap<>();
        //负责更新zk节点时间戳
        Thread updateZKThread = new Thread(() -> {
            while (true) {
                try {
                    List<String> children = zooKeeper.getChildren(ZkConstant.ROOT_NODE, true);
                    for (String child : children) {
                        byte[] data = zooKeeper.getData(ZkConstant.ROOT_NODE + "/" + child, true, null);
                        Long responseTime = Long.valueOf(new String(data, "UTF-8"));
                        addressMap.put(child, responseTime);
                        if (responseTime == addressMap.get(child)) {
                            zooKeeper.setData(ZkConstant.ROOT_NODE + "/" + child, "0".getBytes("UTF-8"), -1);
                            System.out.println("重置请求时间戳成功");
                            addressMap.put(child, 0L);
                        }
                    }
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    CreateNode.init(createNode);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        updateZKThread.setDaemon(true);
        updateZKThread.start();
    }
}
